
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace std;
using namespace cv;

#include "CFrameGrinder.h"

CFrameGrinder::CFrameGrinder()
{
    m_gray = NULL;
    m_thresh = 100;
    m_storage = NULL;
}

CFrameGrinder::~CFrameGrinder()
{
}

void CFrameGrinder::lookForTarget()
{
    try
    {
        // Work on a clone so the orignal image is not altered until the end
        cv::Mat tempImage = m_frame.clone();

        /// Convert it to gray
        cvtColor(tempImage, tempImage, CV_BGR2GRAY);

        /// Reduce the noise so we find the larger shapes
        GaussianBlur(tempImage, tempImage, Size(9, 9), 2, 2);

        cv::threshold(tempImage, tempImage, 128, 255, CV_THRESH_BINARY);


        //Find the contours. Use the contourOutput Mat so the original image doesn't get overwritten
        std::vector<std::vector<cv::Point> > contours;
        cv::findContours(tempImage, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);

        vector<vector<Point> >hull(contours.size());
        for (int i = 0; i < contours.size(); i++)
        {
            convexHull(Mat(contours[i]), hull[i], false);
        }

        /// Draw hull results
        const Scalar color = cv::Scalar(255, 255, 255);
        for (int i = 0; i < contours.size(); i++)
        {
            drawContours(m_frame, hull, i, color, 1, 8, vector<Vec4i>(), 0, Point());
        }
    }
    catch (...)
    {
    }
}

void CFrameGrinder::compress()
{
    m_outbuf.clear();
    m_params.clear();
    m_params.push_back(CV_IMWRITE_JPEG_QUALITY);
    m_params.push_back(8);
    if (!cv::imencode(".jpg", m_frame, m_outbuf, m_params))
    {
        printf("Failed to encode frame to JPG format\n");
    }
}

